/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.lnu.ums.service.impl;

import edu.lnu.ums.dal.IAbstractProcessDAO;
import edu.lnu.ums.dal.IUMSObjectDAO;
import edu.lnu.ums.dal.exception.OldVersionSavingException;
import edu.lnu.ums.dal.factories.FactoriesCache;
import edu.lnu.ums.entities.core.AbstractProcess;
import edu.lnu.ums.entities.core.UMSObject;
import edu.lnu.ums.service.ITreeService;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManagerFactory;


@Stateless
public class TreeService implements ITreeService {

    @EJB(mappedName = "UMS/UMSObjectDAO/local")
    private IUMSObjectDAO umsObjectDAO;

    @EJB(mappedName = "UMS/AbstractProcessDAO/local")
    private IAbstractProcessDAO abstractProcessDAO;

    private UMSObject selectedObject;

    @Override
    public UMSObject getRoot() {
        return umsObjectDAO.getRoot(FactoriesCache.getInstance().getDefaultFactory());
    }

    // for dynamic tree
    @Override
    public UMSObject getRoot(UMSObject currentRoot) {
        return getRoot();
    }

    @Override
    public void changeParent(UMSObject child, UMSObject newParent) {
        umsObjectDAO.changeParent(child, newParent);
    }

    @Override
    public void saveUMSObj(UMSObject obj) throws OldVersionSavingException{
        umsObjectDAO.merge(obj);
    }

    @Override
    public void deleteUMSObj(UMSObject obj) {
        umsObjectDAO.delete(obj);
    }

    @Override
    public void addUMSObj(UMSObject obj) {
        umsObjectDAO.persist(obj.getParent().getFactory(), obj);
    }

    @Override
    public UMSObject getById(UMSObject selectedObject, Long id) {
        if (selectedObject == null) {
            return null;
        }

        return umsObjectDAO.getById(selectedObject.getFactory(), id);
    }

    @Override
    public AbstractProcess getProcessByClassAndObject(Class<?> cls, UMSObject obj) {
        return abstractProcessDAO.getByClassAndTargetObject(cls, obj);
    }

    @Override
    public AbstractProcess saveProcess(AbstractProcess procces) throws OldVersionSavingException {
        return abstractProcessDAO.merge(procces);
    }

}
